import _ from 'lodash'

export function addCSSWithId(cssText, id) {
  if (!cssText) {
    return
  }
  id && removeElementBySelector('#' + id)
  var style = document.createElement('style'), // 创建一个style元素
    head = document.head || document.getElementsByTagName('head')[0] // 获取head元素
  style.type = 'text/css' // 这里必须显示设置style元素的type属性为text/css，否则在ie中不起作用
  id && style.setAttribute('id', id)
  if (style.styleSheet) { // IE
    var func = function () {
      try { // 防止IE中stylesheet数量超过限制而发生错误
        style.styleSheet.cssText = cssText
      } catch (e) {
      
      }
    }
    // 如果当前styleSheet还不能用，则放到异步中则行
    if (style.styleSheet.disabled) {
      setTimeout(func, 10)
    } else {
      func()
    }
  } else { // w3c
    // w3c浏览器中只要创建文本节点插入到style元素中就行了
    var textNode = document.createTextNode(cssText)
    style.appendChild(textNode)
  }
  head.appendChild(style) // 把创建的style元素插入到head中
}

export function removeElementBySelector(selector) {
  let dom = document.querySelector(selector)
  dom && dom.parentNode.removeChild(dom)
}

export function addPrefixToCssText(cssText, prefix) {
  if (!cssText) {
    return ''
  }
  cssText = cssText.trim()
  
  let cssArr = cssText.split('}')
  cssArr.pop()
  cssArr = cssArr.map(one => {
    return prefix + ' ' + one.trim() + '}'
  })
  return cssArr.reduce((one, str) => {
    return one += str
  }, '')
}

export function createElementByHtml(ele) {
  let odiv = document.createElement('div')
  odiv.innerHTML = ele
  return odiv.childNodes
}

export function scrollTo(container, backPosition) {
  backPosition = backPosition || 0
  let promiseResolve
  let promise = new Promise((resolve, reject) => {
    promiseResolve = resolve
  })
  const start = container.scrollTop
  let i = 0
  let interval = setInterval(() => {
    if (start > backPosition) {
      const next = Math.floor(easeInOutQuad(10 * i, start, -start, 500))
      
      if (next <= backPosition) {
        container.scrollTop = backPosition
        promiseResolve()
        clearInterval(interval)
      } else {
        container.scrollTop = next
      }
    } else {
      let n = backPosition - start
      const next = start + n - (Math.floor(easeInOutQuad(10 * i, n, -n, 500)))
      if (next >= backPosition) {
        container.scrollTop = backPosition
        promiseResolve()
        clearInterval(interval)
      } else {
        container.scrollTop = next
      }
    }
    
    i++
  }, 16.7)
  return promise
}

export function easeInOutQuad(t, b, c, d) {
  if ((t /= d / 2) < 1) return c / 2 * t * t + b
  return -c / 2 * (--t * (t - 2) - 1) + b
}

export function findParent(selfNode, selector, allNodeQueryBySelector) {
  if (!selfNode.parentNode) {
    return false
  }
  let rootNode = selfNode.getRootNode()
  let isFindParentNode = false
  if (!allNodeQueryBySelector) {
    allNodeQueryBySelector = rootNode.querySelectorAll(selector)
  }
  
  _.forEach(allNodeQueryBySelector, item => {
    if (item === selfNode.parentNode) {
      isFindParentNode = true
      return true
    }
  })
  if (!isFindParentNode) {
    return findParent(selfNode.parentNode, selector, allNodeQueryBySelector)
  } else {
    return selfNode.parentNode
  }
}

export function findParents(selfNode, selector, allNodeQueryBySelector) {
  let arr = []
  let rootNode = selfNode.getRootNode()
  allNodeQueryBySelector = rootNode.querySelectorAll(selector)
  let find = findParent(selfNode, selector, allNodeQueryBySelector)
  while (find) {
    arr.push(find)
    find = findParent(find, selector, allNodeQueryBySelector)
  }
}

export function getDocPosition(element) {
  let eleCom = element
  let x = eleCom.offsetLeft
  let y = eleCom.offsetTop
  let parent = eleCom.offsetParent
  while (parent) {
    x += parent.offsetLeft
    y += parent.offsetTop
    parent = parent.offsetParent
  }
  return {
    left: x,
    top: y
  }
}

export function svgToBase64(svg) {
  let icon = createElementByHtml(svg)
  if (icon) {
    _.each(icon, one => {
      if (one.tagName.toUpperCase() === 'SVG') {
        icon = one
        return false
      }
    })
  }
  let svgStr = (icon && icon.outerHTML) || ''
  
  return 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svgStr)))
}
